const { find: findOrgUnit } = require('./org-units')

let UserRoles = []

function list(userId) {
  const id = parseInt(userId)
  return UserRoles.filter(item => item.userId === id)
}
function add(orgUnitId, userId, role) {
  const orgUnit = findOrgUnit(orgUnitId)
  const orgUnitName = orgUnit ? orgUnit.name : ''
  const arr = UserRoles.filter(item => item.userId === userId && item.orgUnitId === orgUnitId && item.role === role)
  if (arr.length === 0) {
    UserRoles.push({
      id: UserRoles.length > 1 ? UserRoles[UserRoles.length - 1].id + 1 : 1,
      orgUnitId: orgUnitId,
      orgUnitName: orgUnitName,
      role: role,
      userId: userId
    })
  }
}

function find(id) {
  id = id ? parseInt(id) : null
  for (let i = 0; i < UserRoles.length; ++i) {
    if (UserRoles[i].id === id) {
      return UserRoles[i]
    }
  }
  return null
}

function deleteRecord(id) {
  id = id ? parseInt(id) : null
  if (id) {
    UserRoles = UserRoles.filter(item => item.id !== id)
  }
}

module.exports = { list, add, find, deleteRecord }
